import Cookies from "js-cookie";
import { storageLocal } from "@pureadmin/utils";
import { useUserStoreHook } from "@/store/modules/user";

const TokenKey = "scm-js-Token";
const TokenDef = "scm-Token";
const userTokenKey = "scm-user-info";
const userTokenDef = "scm-user-info-def";

export interface DataInfo<T> {
  /** token */
  accessToken: string;
  /** `accessToken`的过期时间（时间戳） */
  expires: T;
  /** 用于调用刷新accessToken的接口时所需的token */
  refreshToken: string;
  /** 头像 */
  avatar?: string;
  /** 用户名 */
  username?: string;
  /** 昵称 */
  nickname?: string;
  /** 当前登录用户的角色 */
  roles?: Array<string>;
  /** 当前登录用户的按钮级别权限 */
  permissions?: Array<string>;
}

export function getToken() {
  // 此处与`TokenKey`相同，此写法解决初始化时`Cookies`中不存在`TokenKey`报错
  return Cookies.get(TokenKey)
    ? JSON.parse(Cookies.get(TokenKey))
    : storageLocal().getItem(userTokenKey);
}

export function getCopyToken() {
  return Cookies.get(TokenDef)
    ? JSON.parse(Cookies.get(TokenDef))
    : storageLocal().getItem(userTokenDef);
}

export function setCopyToken(data: DataInfo<Date>) {
  let expires = 0;
  const { accessToken, refreshToken, roles } = data;
  expires = new Date(data.expires).getTime(); // 如果后端直接设置时间戳，将此处代码改为expires = data.expires，然后把上面的DataInfo<Date>改成DataInfo<number>即可
  const cookieString = JSON.stringify({
    accessToken,
    expires,
    refreshToken,
    roles
  });

  expires > 0
    ? Cookies.set(TokenDef, cookieString, {
        expires: (expires - Date.now()) / 86400000
      })
    : Cookies.set(TokenDef, cookieString);

  if (data.username && data.roles) {
    const { username, roles } = data;
    setUserKey(
      {
        avatar: data?.avatar ?? "",
        username,
        nickname: data?.nickname ?? "",
        roles,
        permissions: data?.permissions ?? [],
        expires,
        refreshToken
      },
      TokenDef
    );
  } else {
    const avatar =
      storageLocal().getItem<DataInfo<number>>(userTokenDef)?.avatar ?? "";
    const username =
      storageLocal().getItem<DataInfo<number>>(userTokenDef)?.username ?? "";
    const nickname =
      storageLocal().getItem<DataInfo<number>>(userTokenDef)?.nickname ?? "";
    const roles =
      storageLocal().getItem<DataInfo<number>>(userTokenDef)?.roles ?? [];
    const permissions =
      storageLocal().getItem<DataInfo<number>>(userTokenDef)?.permissions ?? [];
    setUserKey(
      {
        avatar,
        username,
        nickname,
        roles,
        permissions,
        expires,
        refreshToken
      },
      TokenDef
    );
  }
}

function setUserKey(
  { avatar, username, nickname, roles, permissions, refreshToken, expires },
  localKey
) {
  useUserStoreHook().SET_AVATAR(avatar);
  useUserStoreHook().SET_USERNAME(username);
  useUserStoreHook().SET_NICKNAME(nickname);
  useUserStoreHook().SET_ROLES(roles);
  useUserStoreHook().SET_PERMS(permissions);
  storageLocal().setItem(localKey, {
    refreshToken,
    expires,
    avatar,
    username,
    nickname,
    roles,
    permissions
  });
}

export function setToken(data: DataInfo<Date>) {
  let expires = 0;
  const { accessToken, refreshToken, roles } = data;
  expires = new Date(data.expires).getTime(); // 如果后端直接设置时间戳，将此处代码改为expires = data.expires，然后把上面的DataInfo<Date>改成DataInfo<number>即可
  const cookieString = JSON.stringify({
    accessToken,
    expires,
    refreshToken,
    roles
  });

  expires > 0
    ? Cookies.set(TokenKey, cookieString, {
        expires: (expires - Date.now()) / 86400000
      })
    : Cookies.set(TokenKey, cookieString);

  if (data.username && data.roles) {
    const { username, roles } = data;
    setUserKey(
      {
        avatar: data?.avatar ?? "",
        username,
        nickname: data?.nickname ?? "",
        roles,
        permissions: data?.permissions ?? [],
        expires,
        refreshToken
      },
      TokenKey
    );
  } else {
    const avatar =
      storageLocal().getItem<DataInfo<number>>(userTokenKey)?.avatar ?? "";
    const username =
      storageLocal().getItem<DataInfo<number>>(userTokenKey)?.username ?? "";
    const nickname =
      storageLocal().getItem<DataInfo<number>>(userTokenKey)?.nickname ?? "";
    const roles =
      storageLocal().getItem<DataInfo<number>>(userTokenKey)?.roles ?? [];
    const permissions =
      storageLocal().getItem<DataInfo<number>>(userTokenKey)?.permissions ?? [];
    setUserKey(
      {
        avatar,
        username,
        nickname,
        roles,
        permissions,
        expires,
        refreshToken
      },
      TokenKey
    );
  }
}

export function removeToken() {
  Cookies.remove(TokenKey);
  storageLocal().removeItem(userTokenKey);
  removeCopyToken();
}

export function removeCopyToken() {
  Cookies.remove(TokenDef);
  storageLocal().removeItem(userTokenDef);
}
